package br.com.educa.log;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

import br.com.educa.modelo.security.Usuario;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

@Configurable
@Entity
@Table(schema = "public")
@RooJavaBean
@RooSerializable
@RooToString
@RooJpaActiveRecord(schema = "public")
@RooJson
public class Log implements Serializable {
	
	private static final long serialVersionUID = 1L;

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

	@Version
    @Column(name = "version")
    private Integer version;
	
	@NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
	private Date dataRegistro = new Date();
	
	@ManyToOne
	@JoinColumn(name = "usuario", referencedColumnName = "id", nullable=true)
	private Usuario usuario;
	
	@NotNull
	private String classe;

	@NotNull
	private String tipoDeRequest;

	@Size(max = 200000)
	private String registro;
	
	@Size(max = 200000)
	private String registroAnterior;
	
	private String ip;
	
	private String porta;

	public Long getId() {
        return this.id;
    }

	public void setId(Long id) {
        this.id = id;
    }

	public Integer getVersion() {
        return this.version;
    }

	public void setVersion(Integer version) {
        this.version = version;
    }

	@PersistenceContext
    transient EntityManager entityManager;

	public static final EntityManager entityManager() {
        EntityManager em = new Log().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

	public static long countLogActions() {
        return entityManager().createQuery("SELECT COUNT(o) FROM LogAction o", Long.class).getSingleResult();
    }

	public static List<Log> findAllLogActions() {
        return entityManager().createQuery("SELECT o FROM LogAction o", Log.class).getResultList();
    }

	public static Log findLogAction(Long id) {
        if (id == null) return null;
        return entityManager().find(Log.class, id);
    }

	public static List<Log> findLogActionEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM LogAction o", Log.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

	@Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

	@Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Log attached = Log.findLogAction(this.id);
            this.entityManager.remove(attached);
        }
    }

	@Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

	@Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

	@Transactional
    public Log merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Log merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

	public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

	public String toJson() {
        return new JSONSerializer().exclude("*.class").serialize(this);
    }

	public static Log fromJsonToLogAction(String json) {
        return new JSONDeserializer<Log>().use(null, Log.class).deserialize(json);
    }

	public static String toJsonArray(Collection<Log> collection) {
        return new JSONSerializer().exclude("*.class").serialize(collection);
    }

	public static Collection<Log> fromJsonArrayToLogActions(String json) {
        return new JSONDeserializer<List<Log>>().use(null, ArrayList.class).use("values", Log.class).deserialize(json);
    }

	public Date getDataRegistro() {
		return dataRegistro;
	}

	public void setDataRegistro(Date dataRegistro) {
		this.dataRegistro = dataRegistro;
	}

	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public String getClasse() {
		return classe;
	}

	public void setClasse(String classe) {
		this.classe = classe;
	}

	public String getTipoDeRequest() {
		return tipoDeRequest;
	}

	public void setTipoDeRequest(String tipoDeRequest) {
		this.tipoDeRequest = tipoDeRequest;
	}

	public String getRegistro() {
		return registro;
	}

	public void setRegistro(String registro) {
		this.registro = registro;
	}

	public String getRegistroAnterior() {
		return registroAnterior;
	}

	public void setRegistroAnterior(String registroAnterior) {
		this.registroAnterior = registroAnterior;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getPorta() {
		return porta;
	}

	public void setPorta(String porta) {
		this.porta = porta;
	}


	public static long countLogs() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Log o", Long.class).getSingleResult();
    }

	public static List<Log> findAllLogs() {
        return entityManager().createQuery("SELECT o FROM Log o", Log.class).getResultList();
    }

	public static Log findLog(Long id) {
        if (id == null) return null;
        return entityManager().find(Log.class, id);
    }

	public static List<Log> findLogEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Log o", Log.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

	public static Log fromJsonToLog(String json) {
        return new JSONDeserializer<Log>().use(null, Log.class).deserialize(json);
    }

	public static Collection<Log> fromJsonArrayToLogs(String json) {
        return new JSONDeserializer<List<Log>>().use(null, ArrayList.class).use("values", Log.class).deserialize(json);
    }
}
